<?php

/**
 * Maikuro CMS
 *
 * LICENSE:
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The license is bundled with this package in the file LICENSE.txt.
 * You may also obtain a copy of the License at this URL:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @copyright  Copyright (c) 2010, Jonathan Hedrén
 * @author     Jonathan Hedrén <jonathan.hedren@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 */

    if (file_exists('../app/etc/config.php')) {
        echo 'It seems like Maikuro CMS is already configured. Please remove the config.php file to continue.';
        exit;
    }

    set_include_path(realpath('../../../trunk/lib/maikuro/') . PATH_SEPARATOR . realpath('../lib/maikurocms/'));

    require_once 'Constants.php';
    require_once 'db/MysqlPDO.php';
    require_once 'Request.php';
    require_once 'cache/FileCacheHandler.php';
    require_once 'form/Form.php';
    require_once 'Translator.php';
    require_once 'SetupForm.php';
    require_once 'service/ServiceFactory.php';
    
    $request = new Request();

    $form = new SetupForm();

    $errorMessage = null;

    if ($request->isPost()) {
        $form->setData($request->getPost());
        if ($form->isValid()) {
            
            try {
                $dbHost = $form->dbHost->getValue();
                $dbUser = $form->dbUsername->getValue();
                $dbPassword = $form->dbPassword->getValue();
                $dbName = $form->dbName->getValue();
                // setup database
                $dbHandler = new MysqlPDO($dbUser, $dbPassword, $dbName, $dbHost);

                // create config.php
                require_once '../app/etc/config.example.php';
                if (!is_array($config)) {
                    // Something is wrong...
                }

                $config['db']['user'] = $dbUser;
                $config['db']['password'] = $dbPassword;
                $config['db']['database'] = $dbName;
                $config['db']['host'] = $dbHost;

                $configFileContents = "<?php\n\$config = "
                                    . var_export($config, true)
                                    . ";";
                if (!file_put_contents('../app/etc/config.php', $configFileContents)) {
                    throw new Exception('Config file not writeable. Please make sure that the /app/etc/ directory is writable.');
                }
                
                require_once 'setup.sql.php';

                $dbHandler->beginTransaction();

                foreach ($queries as $query) {
                    $dbHandler->exec($query);
                }
                $dbHandler->commit();
                
                $serviceFactory = new ServiceFactory($dbHandler, new FileCacheHandler('../app/cache/'), realpath('../'));

                // Create the new site
                $siteService = $serviceFactory->getSiteService();

                $site = $siteService->create();
                $site->name = $form->siteName->getValue();
                $site->code = 'default';
                $site->url = preg_replace('/setup.*$/', '', $request->getApplicationPath());
                $site->theme = 'maikuro';
                $site->timezone = $form->siteTimezone->getValue();

                $siteService->save($site);
                $siteService->purgeCache();

                // Create a root page for the site
                $pageService = $serviceFactory->getPageService();

                $homePageTitle = $form->siteHomePageTitle->getValue();

                $defaultPage = $pageService->create();
                $defaultPage->title = $homePageTitle;
                $defaultPage->content = "<h2>Congratulations!</h2>\n<p>The setup was successful. This is the home page. Go to <a href=\"{$site->url}backend/\">the backend area</a> to start managing the site.</p>";
                $defaultPage->template = 'default';
                $defaultPage->urlTitle = Filters::urlFriendly($homePageTitle);
                $defaultPage->siteId = $site->id;
                $defaultPage->childrenSortOrder = PageEntity::CHILDREN_SORT_ORDER_WEIGHT;
                $defaultPage->status = PageEntity::STATUS_PUBLISHED;
                $now = date('Y-m-d H:i:s');
                $defaultPage->created = $now;
                $defaultPage->updated = $now;

                $pageService->save($defaultPage);
                $pageService->purgeCache($site->id);

                // Create general settings
                $settingService = $serviceFactory->getSettingService();
                $adminSesLifetimeSetting = $settingService->create();
                $adminSesLifetimeSetting->name = 'administratorSessionLifetime';
                $adminSesLifetimeSetting->label = 'Administrator session lifetime';
                $adminSesLifetimeSetting->value = 3600;
//                $defaultLangSetting = $settingService->create();
//                $defaultLangSetting->name = 'defaultLanguage';
//                $defaultLangSetting->label = 'Default language';
//                $defaultLangSetting->value = $form->defaultLanguage->getValue();

                $settingService->save($adminSesLifetimeSetting);
                //$settingService->save($defaultLangSetting);
                $settingService->purgeCache();

                // Create permissions
                $permissionService = $serviceFactory->getPermissionService();
                
                $administratorsPermission = $permissionService->create();
                $administratorsPermission->title = 'Administrators';
                $administratorsPermission->subject = 'administrator';
                $administratorsPermission->type = 'system';
                $pagePermission = $permissionService->create();
                $pagePermission->title = 'Pages';
                $pagePermission->subject = 'page';
                $pagePermission->type = 'content';
                $sitePermission = $permissionService->create();
                $sitePermission->title = 'Sites';
                $sitePermission->subject = 'site';
                $sitePermission->type = 'system';
                $settingPermission = $permissionService->create();
                $settingPermission->title = 'Settings';
                $settingPermission->subject = 'setting';
                $settingPermission->type = 'system';

                $permissionService->save($administratorsPermission);
                $permissionService->save($pagePermission);
                $permissionService->save($settingPermission);
                $permissionService->save($sitePermission);
                $permissionService->purgeCache();

                // Create the administrator
                $administratorService = $serviceFactory->getAdministratorService();

                $administrator = $administratorService->create();

                $administrator->created = date("Y-m-d H:i:s");
                $administrator->email = $form->adminEmail->getValue();
                $administrator->password = hash('md5', $form->adminPassword->getValue() . $administrator->created);
                $administrator->username = $form->adminUsername->getValue();

                // ...with permissions to do anything.
                $permissions = array(
                    $administratorsPermission,
                    $pagePermission,
                    $settingPermission,
                    $sitePermission,
                );
                foreach ($permissions as $permission) {
                    $administratorPermission = $administratorService->createAdministratorPermission();
                    $administratorPermission->permissionId = $permission->id;
                    $administratorPermission->accessLevel = Constants::ACCESS_LEVEL_VIEW_EDIT_CREATE_DELETE;
                    if ($permission->type == 'content') {
                        $administratorPermission->siteId = $site->id;
                    }

                    $administrator->permissions[] = $administratorPermission;
                }

                $administratorService->save($administrator);
                $administratorService->purgeCache();

                $request->redirectTo($site->url);
            } catch (Exception $e) {
                $errorMessage = $e->getMessage();
            }
        }
    }
?>

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Maikuro CMS Setup</title>
        <style type="text/css">
            @import 'setup.css';
        </style>
    </head>
    <body>
        <div id="page">
            <h1>Maikuro CMS Setup</h1>

            <?php if ($errorMessage != null): ?>
            <p><?php echo $errorMessage; ?></p>
            <?php endif; ?>
            <form action="" method="post">
                <fieldset>
                    <legend><?php echo Translator::translate('Database settings'); ?></legend>
                    <?php
                        echo $form->dbHost;
                        echo $form->dbName;
                        echo $form->dbUsername;
                        echo $form->dbPassword;
                    ?>
                </fieldset>

                <fieldset>
                    <legend><?php echo Translator::translate('Site settings'); ?></legend>
                    <?php
                        echo $form->siteName;
                        echo $form->siteHomePageTitle;
                        echo $form->siteTimezone;
                    ?>
                </fieldset>

                <!--fieldset>
                    <legend><?php echo Translator::translate('General settings'); ?></legend>
                    <?php
                        echo $form->defaultLanguage;
                        echo $form->administratorSessionTimeout;
                    ?>
                </fieldset-->

                <fieldset>
                    <legend><?php echo Translator::translate('Administrator user details'); ?></legend>
                    <?php
                        echo $form->adminUsername;
                        echo $form->adminEmail;
                        echo $form->adminPassword;
                    ?>
                </fieldset>

                <div>
                    <input type="submit" value="<?php echo Translator::translate('Submit'); ?>" />
                </div>
            </form>
        </div>
    </body>
</html>